package com.ymt.bpm.engine.listener.activity;

import com.ymt.bpm.appboot.SpringContext;
import com.ymt.bpm.engine.handler.activity.UserTaskDelegate;
import com.ymt.bpm.engine.listener.engine.exception.EngineException;
import com.ymt.bpm.engine.listener.engine.exception.ErrorCode;
import com.ymt.bpm.service.platform.log.SysLogService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;

/**
 * Created by Johnny on 2016/12/24.
 */
public class UserTaskDelegateListener implements TaskListener {

    private UserTaskDelegate utd;

    @Override
    public void notify(DelegateTask delegateTask) {
        try {
            utd = SpringContext.getBean(UserTaskDelegate.class);
            switch (delegateTask.getEventName()) {
                case EVENTNAME_CREATE:
                    utd.onCreate(delegateTask);
                    break;
                case EVENTNAME_ASSIGNMENT:
                    utd.onAssignment(delegateTask);
                    break;
                case EVENTNAME_COMPLETE:
                    utd.onComplete(delegateTask);
                    break;
                case EVENTNAME_DELETE:
                    utd.onDelete(delegateTask);
                    break;
                default:
                    //do nothing
            }
        } catch (Exception e) {
            e.printStackTrace();
            EngineException ee = new EngineException(ErrorCode.PI_FAIL,
                    "UserTaskDelegateListener failed on event:" + delegateTask.getEventName()+", executionId="+delegateTask.getId(),
                    e);
            try {
                SysLogService logService = SpringContext.getBean(SysLogService.class);
                logService.expLog(delegateTask.getTenantId(),
                        delegateTask.getProcessInstanceId(),
                        delegateTask.getTaskDefinitionKey(),
                        "",
                        "0",
                        null, null, e);
            } catch (Exception e1) {
                e.printStackTrace();
            }
            throw new RuntimeException(
                    ee);//for rollback
        }
    }

}
